package com.hongkuncheng.cms.controller.admin;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.Article;
import com.hongkuncheng.cms.model.ArticlePush;
import com.hongkuncheng.cms.model.ArticleState;
import com.hongkuncheng.cms.model.Organization;
import com.hongkuncheng.cms.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 文档报送管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/articlereceive")
public class AarticlereceiveController extends BaseController {

    // 文档列表
    @RequestMapping
    public String index() {
        Criteria criteriaArticlepush = factorySession.createCriteria(ArticlePush.class);
        StringBuilder callbackparams = new StringBuilder();
        String orgname = request.getParameter("orgname") == null ? "" : request.getParameter("orgname");
        if (!orgname.isEmpty()) {
            criteriaArticlepush.add(Restrictions.eq("source", orgname));
            callbackparams.append("&orgname=" + orgname);
        }
        request.setAttribute("orgname", orgname);
        String title = request.getParameter("title") == null ? "" : request.getParameter("title");
        if (!title.isEmpty()) {
            criteriaArticlepush.add(Restrictions.like("title", title, MatchMode.ANYWHERE));
            callbackparams.append("&title=" + title);
        }
        request.setAttribute("title", title);
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        List<ArticlePush> articles = criteriaArticlepush.addOrder(Order.desc("id"))
                .setFirstResult((pageIndex - 1) * datasize).setMaxResults(datasize).list();
        request.setAttribute("articles", articles);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = articles.size() == 0 ? 0 : Integer.parseInt(criteriaArticlepush
                .setProjection(Projections.countDistinct("id"))
                .setFirstResult(0).uniqueResult().toString());
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        List<Organization> organizations = factorySession.createCriteria(Organization.class)
                .add(Restrictions.ne("project", applicationName))
                .add(Restrictions.eq("attach", true)).addOrder(Order.asc("sort"))
                .list();
        request.setAttribute("organizations", organizations);
        return view();
    }

    // 文档详细
    @RequestMapping("detail")
    public String detail() {
        int articleId = Integer.parseInt(request.getParameter("articleid"));
        ArticlePush article = factorySession.get(ArticlePush.class, articleId);
        request.setAttribute("article", article);
        List<Organization> organizations = factorySession.createCriteria(Organization.class).list();
        String pageurl = null;
        for (Organization organization : organizations) {
            if (organization.getName().equals(article.getSource())) {
                pageurl = organization.getOutterhost();
                break;
            }
        }
        if (article.getContents() != null && !article.getContents().isEmpty()) {
            String contents = article.getContents();
            Pattern patternImage = Pattern.compile("src\\s*=\\s*[\"'](?<src>.*?)[\"'](.*?)",
                    Pattern.CASE_INSENSITIVE);
            Matcher matcherImage = patternImage.matcher(contents);
            Set<String> imgurls = new HashSet<>();
            while (matcherImage.find()) {
                String imgurl = matcherImage.group("src");
                if (!imgurl.startsWith("http") && !imgurls.contains(imgurl)) {
                    contents = contents.replace(imgurl, pageurl + imgurl);
                    imgurls.add(imgurl);
                }
            }
            request.setAttribute("contents", contents);
        }
        if (article.getImage() != null && !article.getImage().isEmpty()) {
            String imgurl = article.getImage();
            if (!imgurl.startsWith("http")) imgurl = pageurl + imgurl;
            request.setAttribute("image", imgurl);
        }
        request.setAttribute("callbackparams", request.getParameter("callbackparams"));
        return view();
    }

    // 接收并导入草稿箱
    @RequestMapping("passimport")
    @ResponseBody
    public void passimport() {
        checkAdminPermission("office_article_receive");
        ArticleState articleState = factorySession.load(ArticleState.class, 1);
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        List<Organization> organizations = factorySession.createCriteria(Organization.class).list();
        String[] articleIds = request.getParameter("articleids").split(",");
        List<ArticlePush> articlepushs = factorySession.createCriteria(ArticlePush.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds))).list();
        for (ArticlePush push : articlepushs) {
            String pageurl = null;
            for (Organization organization : organizations) {
                if (organization.getName().equals(push.getSource())) {
                    pageurl = organization.getOutterhost();
                    break;
                }
            }
            Article article = new Article();
            article.setArticleState(articleState);
            article.setAdmin(admin);
            article.setTitle(push.getTitle());
            article.setBold(false);
            article.setRed(false);
            article.setSource(push.getSource());
            article.setAuthor(push.getAuthor());
            article.setDigest(push.getDigest());
            article.setExturl(push.getExturl());
            if (push.getContents() != null && !push.getContents().isEmpty()) {
                String contents = push.getContents();
                Pattern patternImage = Pattern.compile("src\\s*=\\s*[\"'](?<src>.*?)[\"'](.*?)",
                        Pattern.CASE_INSENSITIVE);
                Matcher matcherImage = patternImage.matcher(contents);
                Set<String> imgurls = new HashSet<>();
                while (matcherImage.find()) {
                    String imgurl = matcherImage.group("src");
                    if (!imgurl.startsWith("http") && !imgurls.contains(imgurl)) {
                        contents = contents.replace(imgurl, pageurl + imgurl);
                        imgurls.add(imgurl);
                    }
                }
                article.setContents(contents);
                article.setContenttext(StringHelper.escapeHtml(contents));
            }
            if (push.getImage() != null && !push.getImage().isEmpty()) {
                String imgurl = push.getImage();
                if (!imgurl.startsWith("http")) {
                    imgurl = pageurl + imgurl;
                }
                article.setImage(imgurl);
            }
            article.setPublishtime(new Date());
            article.setClicknum(0);
            article.setSort(0);
            factorySession.save(article);
            factorySession.delete(push);
        }
        recordLog("接收并导入《" + articlepushs.get(0).getTitle().trim() + "》等" + articleIds.length + "篇文档到草稿箱");
        PageHelper.alertAndRedirect("成功接收并导入到草稿箱", "./?" + request.getParameter("callbackparams"));
    }

    // 拒收
    @RequestMapping("turndown")
    @ResponseBody
    public void turndown() {
        checkAdminPermission("office_article_receive");
        String[] articleIds = request.getParameter("articleids").split(",");
        List<ArticlePush> articlepushs = factorySession.createCriteria(ArticlePush.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds))).list();
        for (ArticlePush push : articlepushs) factorySession.delete(push);
        recordLog("拒收《" + articlepushs.get(0).getTitle().trim() + "》等" + articleIds.length + "篇文档");
        PageHelper.alertAndRedirect("拒收成功", "./?" + request.getParameter("callbackparams"));
    }

}
